import { useBoolean } from 'ahooks';
import { Form, Input, InputNumber, Modal } from 'antd';
import React, { useCallback } from 'react';
import request from '@/utils/request';
import { GlobalFormLayout } from '@/layouts/Form';
import CatalogTreeSelect from './CatalogTreeSelect';

function findChildrenCatalogIds(children, ids) {
  children.forEach(child => {
    ids.push(child.catalogId);
    findChildrenCatalogIds(child.children, ids);
  });
}

function EditCatalogModal({ visible, onClose, data, form, onOk }) {
  const { getFieldDecorator, validateFields } = form;
  const { catalogId, parentCatalogId, catalogTitle, sort } = data;
  const [submitting, { setTrue: onSubmitting, setFalse: finishSubmit }] = useBoolean(false);
  const isEdit = !!catalogId;

  const handleSubmit = useCallback(() => {
    validateFields((err, data) => {
      if (!err) {
        onSubmitting();
        if (isEdit) {
          request
            .post('/process/updateCatalog', { data })
            .then(onOk)
            .finally(() => {
              // refresh();
              finishSubmit();
            });
        } else {
          request
            .post('/process/createCatalog', { data })
            .then(onOk)
            .finally(() => {
              // refresh();
              finishSubmit();
            });
        }
      }
    });
  }, [finishSubmit, isEdit, onOk, onSubmitting, validateFields]);

  const disableTreeNode = (node, flattenData) => {
    const self = flattenData.find(item => item.catalogId === catalogId);
    if (!self) {
      return false;
    }
    const disabledCatalogIds = [self.catalogId];
    findChildrenCatalogIds(self.children, disabledCatalogIds);
    return disabledCatalogIds.includes(node.catalogId);
  };

  return (
    <Modal
      title={isEdit ? '编辑目录' : '新增目录'}
      visible={visible}
      onCancel={onClose}
      destroyOnClose
      confirmLoading={submitting}
      onOk={() => handleSubmit()}
    >
      <Form {...GlobalFormLayout}>
        {catalogId ? (
          <Form.Item>
            {getFieldDecorator('catalogId', {
              initialValue: catalogId,
            })(<Input hidden />)}
          </Form.Item>
        ) : null}
        <Form.Item label="上级目录">
          {getFieldDecorator('parentCatalogId', {
            initialValue: parentCatalogId,
          })(<CatalogTreeSelect disableTreeNode={disableTreeNode} />)}
        </Form.Item>
        <Form.Item label="目录标题">
          {getFieldDecorator('catalogTitle', {
            initialValue: catalogTitle,
            rules: [
              {
                required: true,
                message: '目录标题不能为空',
              },
            ],
          })(<Input placeholder="请输入" onPressEnter={handleSubmit} />)}
        </Form.Item>
        {isEdit && (
          <Form.Item label="排序">
            {getFieldDecorator('sort', {
              initialValue: sort || 0,
              rules: [
                {
                  required: true,
                  message: '排序不能为空',
                },
              ],
            })(<InputNumber placeholder="请输入" min={0} />)}
          </Form.Item>
        )}
      </Form>
    </Modal>
  );
}

export default Form.create()(EditCatalogModal);
